package com.zyp.boot02.controller;

import com.zyp.boot02.entity.User;
import com.zyp.boot02.util.DBUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;
import java.util.stream.Stream;

@RestController
public class UserController {
    @RequestMapping("/reg")
    public String reg(User user){
        System.out.println("user = " + user);
        try (
                Connection connection = DBUtil.getConnection();
        ){
            String sql = "SELECT id FROM user WHERE username=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, user.getUsername());

            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                return "用户名已存在!";
            }
            // 用户名不存在，可以注册
            String insertSQL = "INSERT INTO user (id,username,password,nickname) VALUE (NULL,?,?,?)";
            PreparedStatement insertPS = connection.prepareStatement(insertSQL);
            insertPS.setString(1,user.getUsername());
            insertPS.setString(2,user.getPassword());
            insertPS.setString(3,user.getNickname());
            insertPS.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "注册成功！";
    }

    @RequestMapping("/login")
    public String login(User user){
        try (
                Connection connection = DBUtil.getConnection();
        ){
            String sql = "SELECT password FROM user WHERE username = ?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                if (rs.getString(1).equals(user.getPassword())){
                    return "登录成功，欢迎回来！";
                }
                return "密码错误，请重试！";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "用户不存在！";
    }
}
